Repository navigation
feat(core): embed structured design context in synthesized templates (MetadataContext) - #38381
Conversation
✅ Updated pull request passes all PRLinter validations. Dismissing previous PRLinter review.
8da308b to
517cab1
Compare
mrgrain
left a comment
There was a problem hiding this comment.
Hey, since the feature is already stable, the Mixin should go straight into aws-cdk-lib as well. The preview package is being phased out.
b362a0a to
b6106b6
Compare
Sounds good, updated |
b6106b6 to
5caa8fa
Compare
|
👋 It looks like your PR description follows the template but is missing a valid issue number in the first section. PRs without a linked issue will receive lower priority for review and merging. Please update the description to include a reference like |
There was a problem hiding this comment.
See the review summary comment for the overview; the notes below are inline.
| } | ||
| if (context.mutability !== undefined) { | ||
| if (Token.isUnresolved(context.mutability)) { | ||
| out.mutability = context.mutability; | ||
| } else { | ||
| const entries = Object.entries(context.mutability); | ||
| const deviations = entries.filter(([, level]) => level !== context.mutable); | ||
| if (entries.length === 0 || deviations.length > 0) { | ||
| out.mutability = Object.fromEntries(deviations); | ||
| } |
There was a problem hiding this comment.
🟡 Recommended — renderResourceContext has a dedicated branch for an unresolved mutability map that passes the token through verbatim and short-circuits the entries/deviations filtering, because iterating a token map with Object.entries() would be wrong. The unit suite exercises token/Lazy inputs only for the list fields (must, deps), never for mutability, so this is the one branch of renderResourceContext with no asserting test. If the guard regressed — falling through to Object.entries() on the token and throwing, or silently dropping the map — the suite would stay green. A Token.isUnresolved guard owes a test that passes an unresolved token through it (AGENTS.md#unit-tests).
Suggested change: Add a resource-level test alongside the existing Lazy test that sets mutability to an unresolved token (e.g. Lazy.any({ produce: () => ({ QueueName: 'must-never-change' }) })) and asserts the rendered Metadata contains the resolved map unchanged (including an entry that would otherwise be filtered as redundant), locking in that the token is passed through without the sparse-deviation filtering.
| CDK can embed structured, advisory context into the | ||
| `Metadata["com.aws.cloudformation.Context"]` sections of synthesized CloudFormation | ||
| templates. It captures the *why* behind your infrastructure — rationale, hard | ||
| invariants, change-safety and provenance — so that humans and | ||
| automated tools working with the deployed template later can act on the author's | ||
| intent instead of guessing it. The structural source of truth is the published | ||
| [AWS CloudFormation `Metadata` Context schema](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-metadata.html#aws-attribute-metadata-context-schema): | ||
| every field it defines is optional, and it sets no `minLength`/`minItems`, so | ||
| blank strings and empty arrays are structurally valid. The schema is advisory — | ||
| CloudFormation does not validate or enforce `Metadata` fields. CDK property names | ||
| are the schema's field names (`why`, `must`, `mutable`, `mutability`, `trust.src`, | ||
| `trust.conf`, `trust.cite`, `trust.note`, `deps`; `arch`, `must`, `ref`, `owner`), | ||
| so code and template use one vocabulary. CDK adds typed enums, targeting, and | ||
| the validation described below. |
There was a problem hiding this comment.
No need.
| CDK can embed structured, advisory context into the | |
| `Metadata["com.aws.cloudformation.Context"]` sections of synthesized CloudFormation | |
| templates. It captures the *why* behind your infrastructure — rationale, hard | |
| invariants, change-safety and provenance — so that humans and | |
| automated tools working with the deployed template later can act on the author's | |
| intent instead of guessing it. The structural source of truth is the published | |
| [AWS CloudFormation `Metadata` Context schema](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-metadata.html#aws-attribute-metadata-context-schema): | |
| every field it defines is optional, and it sets no `minLength`/`minItems`, so | |
| blank strings and empty arrays are structurally valid. The schema is advisory — | |
| CloudFormation does not validate or enforce `Metadata` fields. CDK property names | |
| are the schema's field names (`why`, `must`, `mutable`, `mutability`, `trust.src`, | |
| `trust.conf`, `trust.cite`, `trust.note`, `deps`; `arch`, `must`, `ref`, `owner`), | |
| so code and template use one vocabulary. CDK adds typed enums, targeting, and | |
| the validation described below. | |
| CDK offers structured API to populate the [CloudFormation Metadata Context attribute](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-metadata.html#aws-attribute-metadata-context-schema) |
There was a problem hiding this comment.
All the functions in this file are only imported by metadata-context.ts - move them over there.
| out.mutability = context.mutability; | ||
| } else { | ||
| const entries = Object.entries(context.mutability); | ||
| const deviations = entries.filter(([, level]) => level !== context.mutable); |
There was a problem hiding this comment.
Is this to save maybe 1 or 2 redundant declarations the customer made (explicitly) by mistake? Not worth it - leave as is.
| export const METADATA_CONTEXT_KEY = 'com.aws.cloudformation.Context'; | ||
|
|
||
| export function renderResourceContext(context: CfnResourceMetadataContextProps): Record<string, any> { | ||
| const out: Record<string, any> = {}; |
There was a problem hiding this comment.
Why did you decide to copy the entire props object? We don't usually do that, there are plenty of structs being passed by references to the underlying L1. Not to mention that all the properties are readonly so a mutation is not expected.
| } | ||
| if (context.trust !== undefined) { | ||
| const trust: Record<string, any> = {}; | ||
| if (context.trust.src !== undefined) { |
There was a problem hiding this comment.
How can context.trust.src be undefined if src is required? Feels like your coding against the compiler here.
Please simplify, this entire function can be dropped - just pass the struct as is.
| omitted. Both fields record what the team considers safe to change, not what | ||
| CloudFormation can change in place. | ||
|
|
||
| ### Targeting: exactly what receives context |
There was a problem hiding this comment.
Reduce this entire section to:
- Specify the default selection (
defaultChild). - Mention there is a
selectorproperty to select other resources.
Thats it. Please do not repeat or list all the available APIs - thats why we have ref docs.
| resources are inside Stages selects nothing and fails. Set context inside each | ||
| Stage; this also lets environments carry different guidance: | ||
|
|
||
| ```typescript |
There was a problem hiding this comment.
This example is trivial because it just sets a context of two different scopes. Not needed.
|
|
||
| Context can be set or cleared on resources in a `NestedStack`. Calls do not apply | ||
| across a `Stage`: each Stage is synthesized as its own cloud assembly and Aspects | ||
| are invoked separately for each assembly, so a call on an `App` whose only |
There was a problem hiding this comment.
so a call on an
Appwhose only
Maybe this is the example you wanted to show, but don't think its necessary - too much of an edge case
| }); | ||
|
|
||
| // A helper the L2 exposes; set when the function was created with a dead-letter queue. | ||
| if (lambdaFunction.deadLetterQueue) { |
There was a problem hiding this comment.
I know I asked you for this example before but I think its not needed now, its obvious.
| }); | ||
| ``` | ||
|
|
||
| For an L3 pattern (or any multi-resource construct) with no `defaultChild`, |
There was a problem hiding this comment.
Not needed as a new example, just say the same mechanism can be used for an L2 and L3.
|
Tick the box to add this pull request to the merge queue (same as
|
1 similar comment
|
Tick the box to add this pull request to the merge queue (same as
|
…and aspect + mixins to set context on a resource and template
…ib core The mixins-preview package is being phased out and the feature is stable, so the Mixin ships directly in aws-cdk-lib alongside the MetadataContext facade (review feedback). - MetadataContextMixin now lives in core/lib/mixins/ and is exported flat from aws-cdk-lib (a top-level 'mixins' jsii submodule is not possible: JSII5011 name conflict with the Mixins class), with an awslint exclusion for the mixin-namespace rule. - Unit test moved to core/test/mixins/, adapted to core's toCloudFormation convention. - Integ test moved to @aws-cdk-testing/framework-integ test/core/test/ with regenerated snapshot. - aws-cdk-lib README documents the mixin inline; all mixins-preview changes reverted.
|
Thank you for contributing! Your pull request will be updated from main and then merged automatically (do not update manually, and be sure to allow changes to be pushed to your fork). |
✅ Merged into
|
|
Thank you for contributing! Your pull request will be updated from main and then merged automatically (do not update manually, and be sure to allow changes to be pushed to your fork). |
|
Comments on closed issues and PRs are hard for our team to see. |
Issue # (if applicable)
RFC tracking issue: aws/aws-cdk-rfcs#994
Accepted RFC: aws/aws-cdk-rfcs#981
Reason for this change
CloudFormation templates preserve deployed configuration but usually lose the rationale, invariants, change-safety guidance, and provenance available in CDK source. CloudFormation defines the advisory
com.aws.cloudformation.Contextmetadata schema for preserving that information, but CDK users need a typed authoring API.Description of changes
CfnResourceMetadataContextfor setting or clearing Context on selectedCfnResourceconstructs during synthesis.CfnTemplateMetadataContextfor setting or clearing template-level Context.IConstructSelectorfor explicit resource targeting. The default selects aCfnResourcescope or its immediateCfnResourcedefault child.NestedStackbehavior and does not crossStageassembly boundaries.CfnResource, and unresolved values in top-level template Context.The public API and stable-release plan were approved in RFC 994. The approved surface keeps resource Context separate from targeting options. jsii generates Python as
set(context, *, priority=None, selector=None)and Java asset(context)orset(context, options). RFC 994 also requires rejecting amutabilityentry that repeats the resource-levelmutabledefault so the map remains sparse. Existing applications synthesize unchanged unless they call the new APIs.Checklist
By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license